package com.mall.web.service.user.impl;

import com.mall.base.pojo.Comment;
import com.mall.base.pojo.SecondReply;
import com.mall.base.pojo.ThirdReply;
import com.mall.web.dao.user.CommentMapper;
import com.mall.web.dao.user.ReplyMapper;
import com.mall.web.dao.user.UserMapper;
import com.mall.web.service.user.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {

  @Autowired private CommentMapper commentMapper;

  @Autowired private ReplyMapper replyMapper;

  @Autowired private UserMapper userMapper;

  @Override
  public List<Comment> selectComment(long topicid, int page) {

    // 根据topicid也就是productid分页查询评论

    // 一级
    List<Comment> comments = commentMapper.selectCommentByTopicAndPage(topicid, page);

    // format：
    // 一级评论111
    //     二级评论22
    //      多级评论33
    // 一级评论222
    //      二级评论333
    //      三级评论666

    if (comments != null && comments.size() > 0) {

      for (Comment comment : comments) {

        // 二级评论
        List<SecondReply> secondReply = replyMapper.selectSecondReply(comment.getId(), 0);

        for (SecondReply reply : secondReply) {

          // 多级评论
          List<ThirdReply> thirdReply = replyMapper.selectThirdReply(reply.getId());

          // 因为thirdreply是没有被回复者名字的，所以得查
          thirdReply.forEach(
              e -> {
                String toUsername = userMapper.selectUsernameById(e.getToUser().getId());

                e.getToUser().setUsername(toUsername);
              });
          reply.setThirdReplies(thirdReply);
        }
        comment.setSecondReplies(secondReply);
      }

      return comments;
    }
    else {

      return null;
    }
  }
}
